import React from 'react';
import { Toast,Modal } from 'antd-mobile';
import ReactPullLoad, { STATS } from "react-pullload";
import "../../../../node_modules/react-pullload/dist/ReactPullLoad.css";
import BenzAMRRecorder from 'benz-amr-recorder';

const prompt = Modal.prompt;
var amr = new BenzAMRRecorder();

export default class Index extends React.Component {
    constructor(props){
        super(props)
        this.state={
			id: props.match.params.id,
			imgs: [],
			hasMore: true,
			data:[],
			action: STATS.init,
			page: 1,
			type:1,
			iconFlag:false,
		}
    }
	componentDidMount(){
		document.title = '详情'
        global.Ajax.hhtc_request("dynamic/detail",{id: this.state.id}).then(data=>{
			if(data.code===1){
				this.setState(data.data)
            }
		})
		this.getList()
	}
	getList(){
		var req={
            page: 1,
			size: 12,
			id: this.state.id,
        }
        global.Ajax.hhtc_request("dynamic/pinglunlist",req).then(data=>{
					console.log('data: ', data);
			if(data.code===1){
				var hasMore;
                if(data.data.length>0){
					this.state.page++
					hasMore=true
                }else{
					hasMore=false
				}
                this.setState({
                    data: data.data,
                    hasMore: hasMore,
                    page: this.state.page,
                });
            }
		})
	}
	// 获取商品
	handleAction = action => {
		console.info(action, this.state.action, action === this.state.action);
		//new action must do not equel to old action
		if (action === this.state.action) {
		  	return false;
		}
		if (action === STATS.refreshing) {
		  	//刷新
		  	this.handRefreshing();
		} else if (action === STATS.loading) {
		  	//加载更多
		  	this.handLoadMore();
		} else {
		  	//DO NOT modify below code
		  	this.setState({
				action: action
		  	});
		}
	};	
	handRefreshing = () => {
		if (STATS.refreshing === this.state.action) {
		  	return false;
		}
        var req={
            page: 1,
			size: 12,
			id: this.state.id,
        }
        global.Ajax.hhtc_request("dynamic/pinglunlist",req).then(data=>{
			if(data.code===1){
				var hasMore;
                if(data.data.length>0){
					this.state.page++
					hasMore=true
                }else{
					hasMore=false
				}
                this.setState({
                    data: data.data,
                    hasMore: hasMore,
                    action: STATS.refreshed,
                    page: this.state.page,
                });
            }
		})
		this.setState({
		  	action: STATS.refreshing
		});
	};
	handLoadMore = () => {
		if (STATS.loading === this.state.action) {
		  	return false;
		}
		//无更多内容则不执行后面逻辑
		if (!this.state.hasMore) {
		  	return;
        }
        var req={
            page: this.state.page,
			size: 12,
			id: this.state.id
        }
        global.Ajax.hhtc_request("dynamic/pinglunlist",req).then(data=>{
			if(data.code===1){
                if(data.data.length>0){
					this.setState({
                        data: this.state.data.concat(data.data),
                        action: STATS.reset,
                    });
				}else{
					this.setState({
                        action: STATS.reset,
                        hasMore: false
                    });
				}
            }
		})
		this.setState({
		  	action: STATS.loading
		});
	};
	// 献花
	xh(id,is_self){
		if(is_self===1){
			return Toast.fail('不能给自己打赏!',1)
		}
		prompt(<p><img alt='' src={require('../../imgs/hua.png')} style={{display: 'block',width: '9.334vw',margin: '0 auto'}} /></p>, '',[{
			text: '取消',
			onPress: value => new Promise((resolve) => {
				resolve();
			}),
        }, {
			text: '打赏',
			onPress: value => new Promise((resolve, reject) => {
				if (value*1+'' === 'NaN'){
					return Toast.fail('只能输入数字噢!',1)
				}
				if(value!==''){
					global.Ajax.hhtc_request("dynamic/dashang",{id: id,num: value}).then(data=>{
						if(data.code===1){
							Toast.success(data.msg,1)
							resolve();
						}else{
							Toast.fail(data.msg,1)
						}
					})
				}else{
					Toast.fail('请输入打赏数量')
				}
			}),
        },], 'default', null, ['请输入要打赏的小红花数量'])
	}

	// 点击播放按钮
	playVoice(url){
		amr = new BenzAMRRecorder();
		var iconFlag = !this.state.iconFlag;   // 这个变量是控制播放与否的
		var that = this;
        amr.initWithUrl(url).then(function() {
			amr.play();
			that.setState({
				iconFlag:iconFlag
			})
        });
        // 监听播放完成
        amr.onEnded(()=>{
			this.setState({
				iconFlag:false
			})
		})
	}
	paused(){
		var iconFlag = !this.state.iconFlag;   // 这个变量是控制播放与否的
		amr.stop();
		this.setState({
			iconFlag:iconFlag
		})
	}
	
	render(){
		return(
			<div className='' style={{paddingBottom: 70,}}>
				<div className='sq_list'>
					<div className='item' style={{borderBottom: 10,borderBottomColor: '#F5F5F5',borderBottomStyle: 'solid'}}>
						<div className='head_box'>
							<img alt='' src={this.state.avatar} className='head' />
							<div className='cen'>
								<p className='name'>{this.state.nickname}</p>
								<p className='time'>{this.state.time}</p>
							</div>
						</div>
						<div className='txt_box txt_box1'>
							<p className='desc'>{this.state.content}</p>
							{this.state.imgs.length>0&&<div className='img_btn'>
								{this.state.imgs.map((item,index)=>{
									if (this.state.type==1) {
										return(
											<img key={'img'+index} alt='' src={item} />
										)
									}
									if (this.state.type==2) {
										if (item.indexOf('.amr')) {
											return(
												<div key={'img'+index}>
													<button onClick={this.state.iconFlag?this.paused.bind(this):this.playVoice.bind(this,item)} style={{'border': 'none','width': '10vw','backgroundColor': '#ccc','color': '#fff','borderRadius': '10px','height': '5vw',marginBottom: 10,}}>{this.state.iconFlag?'暂停':'播放'}</button>
												</div>
											)
										}
										else {
											return(
												<audio key={'img'+index} autoplay controls src={item}></audio>
											)
										}
									}
									if (this.state.type==3) {
										return(
											<video style={{'maxWidth':'100%'}} key={'img'+index} controls src={item}></video>
										)
									}
								})}
							</div>}
						</div>
                        {this.state.is_self===0&&<div className='sq_hua'>
                            <p className='wz'>觉得文章不错，就献朵花吧</p>
                            <p className='hua_btn' onClick={this.xh.bind(this,this.state.id,this.state.is_self)}>
                                <img alt='' src={require('../../imgs/hua.png')} className='hua' />
                                <p>献花</p>
                            </p>
                        </div>}
					</div>
				</div>
				<ReactPullLoad
					downEnough={100}
					action={this.state.action}
					handleAction={this.handleAction}
					hasMore={this.state.hasMore}
					distanceBottom={100}
				>
					<div className='sq_comment_list'>
						<h1>全部评论({this.state.comment_num})</h1>
						{this.state.data.map((item,index)=>{
							return(
								<div key={'list'+index} className='item'>
									<div className='head_box'>
										<img alt='' src={item.avatar} className='head' />
										<div className='cen'>
											<p className='name'>{item.nickname}</p>
											<p className='time'>{item.time}</p>
										</div>
									</div>
									<p className='desc'>{item.content}</p>
								</div>
							)
						})}
					</div>
				</ReactPullLoad>
                {/* <div className='sq_comment_list'>                    
                    <div className='item'>
                        <div className='head_box'>
							<img alt='' src={require('../../imgs/head.png')} className='head' />
							<div className='cen'>
								<p className='name'>小白白</p>
								<p className='time'>15小时前</p>
							</div>
						</div>
                        <p className='desc'>情商即是情景的处理。在处于一件事情是选择最有还是最优的一种处理方式，而不是放任本能的情绪。喜怒哀乐是每个人的本能，但是我们消化不好就会传染给别人。高情商及时处理这些喜怒哀乐。</p>
                    </div>
                </div> */}
                <div className='sq_edit_box' onClick={()=>{this.props.history.push('/page/home/square/sendcomment/'+this.state.id)}}>
                    <p>写留言，与大家互动~</p>
                </div>
			</div>
		)
	}
}
